package org.xinghai.sql.dialogue.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.xinghai.sql.dialogue.dto.DeepSeekDto;
import org.xinghai.sql.dialogue.service.DeepSeekService;

import java.util.Arrays;

@Service
public class DeepSeekServiceImpl implements DeepSeekService {
    @Override
    public void getDeepSeekResponse(DeepSeekDto deepSeekDto, ResponseBodyEmitter emitter,StringBuilder sb,String query) {
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content("历史对话"+query+"当前信息："+deepSeekDto.getQuery())
                    .build();

            Flowable<GenerationResult> result = gen.streamCall(GenerationParam.builder()
                    .apiKey(deepSeekDto.getApiKey())
                    .model(deepSeekDto.getModel())
                    .messages(Arrays.asList(userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .incrementalOutput(true)
                    .build());

            // 流式响应处理
            result.blockingForEach(message -> {
                String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
                String content = message.getOutput().getChoices().get(0).getMessage().getContent();

                try {
                    if (!reasoning.isEmpty()) {
                        emitter.send("【思考过程】" + reasoning );
                    }
                    if (!content.isEmpty()) {
                        emitter.send("【完整回复】" + content );
                        sb.append(content);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("流式输出异常", e);
                }
            });

            emitter.complete();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            emitter.completeWithError(e);
        } catch (Exception e) {
            emitter.completeWithError(e);
        }
    }

    @Override
    public String getDeepSeekResponseNotStream(DeepSeekDto deepSeekDto, ResponseBodyEmitter emitter, StringBuilder sb, String query) {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你的名字是星海，专门帮助我们在编程上的问题")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("历史对话"+query+"当前信息："+deepSeekDto.getQuery())
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(deepSeekDto.getApiKey())
                .model(deepSeekDto.getModel())
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();

        GenerationResult result = null;
        try {
            result = gen.call(param);
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        } catch (InputRequiredException e) {
            throw new RuntimeException(e);
        }
        return result.getOutput().getChoices().get(0).getMessage().getContent();
    }
}
